package demo.huodongbaoming.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务发现测试控制器
 */
@RestController
@RequestMapping("/api/discovery")
public class ServiceDiscoveryController {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有服务实例
     * @return 服务列表
     */
    @GetMapping("/services")
    public Map<String, Object> getServices() {
        List<String> services = discoveryClient.getServices();
        Map<String, Object> result = new HashMap<>();
        result.put("services", services);
        result.put("count", services.size());
        return result;
    }

    /**
     * 获取指定服务的所有实例
     * @param serviceId 服务ID
     * @return 服务实例列表
     */
    @GetMapping("/services/{serviceId}")
    public List<Map<String, Object>> getServiceInstances(@PathVariable String serviceId) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        return instances.stream().map(instance -> {
            Map<String, Object> instanceInfo = new HashMap<>();
            instanceInfo.put("serviceId", instance.getServiceId());
            instanceInfo.put("host", instance.getHost());
            instanceInfo.put("port", instance.getPort());
            instanceInfo.put("uri", instance.getUri().toString());
            instanceInfo.put("metadata", instance.getMetadata());
            return instanceInfo;
        }).collect(Collectors.toList());
    }

    /**
     * 提供用户活动数据的API（被失物招领系统调用）
     * @param userId 用户ID
     * @return 用户活动列表
     */
    @GetMapping("/user/{userId}/activities")
    public List<Map<String, Object>> getUserActivities(@PathVariable Long userId) {
        // 这里简单模拟数据，实际应该从数据库查询
        List<Map<String, Object>> activities = new ArrayList<>();
        activities.add(createActivity(1L, "社区志愿服务", "2023-05-15", "已完成", userId));
        activities.add(createActivity(2L, "校园文化节", "2023-06-01", "进行中", userId));
        activities.add(createActivity(3L, "科技创新大赛", "2023-07-10", "未开始", userId));
        return activities;
    }
    
    private Map<String, Object> createActivity(Long id, String name, String date, String status, Long userId) {
        Map<String, Object> activity = new HashMap<>();
        activity.put("id", id);
        activity.put("name", name);
        activity.put("date", date);
        activity.put("status", status);
        activity.put("userId", userId);
        return activity;
    }
} 